﻿/*
 * Author: Duncan Jenkins
 * 
 * Description: Turns a image into binary format, white and black, based on entered threshold
 * */

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Windows.Forms;

namespace LibraryCS {
    public class Binarize : VisionAlgorithm {
        private int Threshold;

        public Binarize(String name) : base(name) { }

        public override Bitmap DoAlgorithm(Bitmap sourceImage) {
            VImage source = new VImage(sourceImage);

            // Threshold the image
            for (int i = 0; i < source.GrayPixels.Length; i++) {
                if (source.GrayPixels[i] > Threshold) {
                    // Part of the foreground, make it white
                    source.RedPixels[i] = 255;
                    source.GreenPixels[i] = 255;
                    source.BluePixels[i] = 255;
                } else {
                    // Part of the background, leave it black
                    source.RedPixels[i] = 0;
                    source.GreenPixels[i] = 0;
                    source.BluePixels[i] = 0;
                }
            }

            source.ApplyPixelChanges();

            return source.localImage;
        }

        #region GUI Functions

        public override System.Collections.Generic.List<System.Windows.Forms.Control> createControls() {
            List<Control> Controls = new List<Control>();

            // Create a Label indictating the type of setting this is
            Label lbThreshold = new Label();
            lbThreshold.AutoSize = true;
            lbThreshold.Text = "Threshold";
            lbThreshold.Name = "lbThreshold";

            // Create a TextBox Control for setting the percentage of noise
            TextBox tbThreshold = new TextBox();
            tbThreshold.Name = "tbThreshold";
            tbThreshold.AcceptsReturn = false;
            tbThreshold.MaxLength = 3;
            tbThreshold.Multiline = false;
            tbThreshold.Size = new Size(50, 25);

            // Add the controls to the list
            Controls.Add(tbThreshold);
            Controls.Add(lbThreshold);

            // Return the list
            return Controls;
        }

        public override void setSettings(System.Collections.Generic.List<object> settings) {
            Threshold = Int32.Parse(((TextBox)settings[0]).Text);
            Debug.WriteLine("Settings entered: " + Threshold);
        }

        #endregion
    }
}
